import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";

import { UserInfoAPI } from "@/request/api/userInfo";
import { useUserStore } from "@/store/user";
import LoginVue from "@/views/Login/Login.vue";
import HomeVue from "@/views/home/Home.vue";
import { ElMessage } from "element-plus";

const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    component: LoginVue,
  },
  {
    path: "/",
    redirect: "/index",
  },
  {
    path: "/",
    component: HomeVue,
    children: [
      {
        path: "index",
        component: () => import("../views/index/Index.vue"),
      },
    ],
  },
];

const router = createRouter({
  routes,
  history: createWebHashHistory(),
});

router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  let token = localStorage.getItem("token");
  if (userStore.menus.length === 0 && token) {
    UserInfoAPI().then((res) => {
      if (res.code === 200) {
        // 把数据存到pinia
        userStore.menus = res.data.menus;
        // 添加用户名
        userStore.username = res.data.username;
        userStore.router.forEach((p) => {
          const route: RouteRecordRaw = {
            path: "/" + p.name,
            name: p.name,
            meta: {
              title: p.title,
            },
            component: () => import("../views/home/Home.vue"),
            children: p.children.map((item) => ({
              path: item.name,
              name: item.name,
              meta: {
                title: item.title,
              },
              component: () => import(`../views/${p.name}/${item.name}.vue`),
            })),
          };
          // 重定向父级第一个子菜单
          if (p.children[0]) {
            route.redirect = `/${p.name}/${p.children[0].name}`;
          }
          router.addRoute(route);
        });
        next(to.fullPath);
      }
    });
    // 判断有无token，如果没有token，并且访问的不是login页面就跳转回login页面
  } else if (!token && to.path !== "/login") {
    ElMessage.error("请先登录");
    next("/login");
  }
  // 如果已经登录，不能通过url直接返回登录页
  else if (token && userStore.menus.length !== 0 && to.path === "/login") {
    // 不让用户访问登录页，跳转回原来的登录页
    next(from.fullPath);
  } else {
    // console.log(router.getRoutes());
    next();
  }
});

export default router;
